<?php

class Model_Forum_Thread extends Forum_Db_Table
{
	protected $_name = 'forum_thread';
    
    protected $_primary = 'id';
	
	
	public function getById($id){
		if(isset($id)){
			$query = "SELECT *
	                  FROM {$this->_name}
					  WHERE status = 'approved' AND id = {$id}";
	
	        return $this->getAdapter()->fetchRow($query);			
		}
		return null;
	}
	
    /**
     * Get list of group_forum
     * 
     * @return array
     */
    public function getList($mode = 'approved'){
        $query = "SELECT ft.*, f.title AS forum
            FROM {$this->_name} AS ft
            LEFT JOIN forum AS f ON f.id = ft.forum_id";

        if ($mode != 'all') {
            $query .= " WHERE ft.status = '{$mode}'";
        }
        
        $query .= " ORDER BY ft.created_on DESC";
        
        return $this->getAdapter()->fetchAll($query);
    }

    /**
     * Get list of forum by id
     * 
     * @return array
     */
    public function getListInForum($id){
        $query = "SELECT *, UNIX_TIMESTAMP(created_on) AS created_on
            FROM {$this->_name} 
            WHERE status = 'approved' AND forum_id = {$id}";

       
        return $this->getAdapter()->fetchAll($query);
    }

    
	/**
	* Get count of threads in forum 
	* 
	* @return array
	*/
	public function getListCount(){
        $query = "SELECT forum_id, count(*) as `count`
                  FROM {$this->_name}
				  WHERE status = 'approved'
				  GROUP BY forum_id";

        return $this->getAdapter()->fetchAll($query);		
	}
	
	/**
	* Get count of threads in forum by forum id
	* 
	* @return array
	*/
	public function getListCountById($listForumId){
		if( !is_array($listForumId) ){ return false; }
		
		$listArr = implode (", ", $listForumId);
		
        $query = "SELECT forum_id, count(*) as `count`
                  FROM {$this->_name}
				  WHERE status = 'approved' AND forum_id in ({$listArr})
				  GROUP BY forum_id";

        return $this->getAdapter()->fetchAll($query);		
	}
	
    /**
     * Updates thread row according to $bind param
     * 
     * @param mixed $ids
     * @param array $bind Column => Value pairs
     * @return bool
     */
    public function update($ids, $bind)
    {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        
        $count = count($ids);
        $ids = implode(',', $ids);
        
        if ($this->getAdapter()->update($this->_name, $bind, array("id IN ({$ids})"))) {
            Forum_Message::getInstance()->addSuccess(sprintf('%d %s успішно оновлено', $count, (
                $count > 4 ? 'тем' : (
                    $count > 1 ? 'теми' : 'тему' //this is wrong, and i know this :/
                )
            )));
            return true;
        } else {
            Forum_Message::getInstance()->addError('Записи не були оновлені. Спробуйте ще раз');
            return false;
        }
    }
    
    /**
     * Delete thread rows by ids
     * 
     * @param mixed $id
     * @return bool
     */
    public function delete($ids)
    {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        
        $count = count($ids);
        $ids = implode(',', $ids);
        
        if ($this->getAdapter()->delete($this->_name, "id IN ({$ids})")) {
            Forum_Message::getInstance()->addSuccess(sprintf('%d %s успішно видалено', $count, (
                $count > 4 ? 'тем' : (
                    $count > 1 ? 'теми' : 'тему' //this is wrong, and i know this :/
                )
            )));
            return true;
        } else {
            Forum_Message::getInstance()->addError('Записи не були видалені. Спробуйте ще раз');
            return false;
        }
    }

	public function add($thread){
		if(is_array($thread)){
			$error = false;
			if(!isset($thread['title']) || empty($thread['title'])){
				Forum_Message::getInstance()->addError("Вкажіть назву теми");
				$error = true;
			}
			if(!isset($thread['forum_id']) || empty($thread['forum_id'])){
				Forum_Message::getInstance()->addError("Не потрібно хитрувати");
				$error = true;
			}
			if($error){
				return false;
			}else{
				if(Model_User::getUserId()){
					$thread['user_id'] = Model_User::getUserId();
				}
				$thread['created_on'] = date('Y-m-d H:i:s');;
				if($this->getAdapter()->insert($this->_name, $thread)){
					Forum_Message::getInstance()->addSuccess("Нову тему створено");
					return true;
				}else{
					Forum_Message::getInstance()->addError("Помилка при при створенні нової теми");
					return false;
				}
			}
			return false;
		}

	}

}

?>